package com.hx.chain;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author Huathy
 * @date 2021-09-23 21:40
 * @description
 */
public class PreProcessor extends Thread implements IRequestProcessor{
    LinkedBlockingQueue<Request> requests = new LinkedBlockingQueue<>();

    private IRequestProcessor nextProcessor;

    private volatile boolean isFinish = false;

    public PreProcessor(IRequestProcessor requestProcessor){
        this.nextProcessor = requestProcessor;
    }

    public PreProcessor() {

    }

    /**
     * 对外提供关闭方法
     */
    public void shutdown(){
        isFinish = true;
    }

    @Override
    public void run() {
        while (!isFinish){
            try {
                //阻塞式获取数据
                Request req = requests.take();
                //todo  真正的处理逻辑
                System.out.println("preProcessor:" + req);
                //处理完后交给下一任责任链
                if(nextProcessor != null){
                    nextProcessor.process(req);
                }
            } catch (InterruptedException e) {
                //所有和阻塞相关的代码都会抛出异常：InterruptedException
                e.printStackTrace();
            }
        }
    }

    @Override
    public void process(Request request) {
        //  todo 根据实际需求做处理
        requests.add(request);
//        nextProcessor.process(request);
    }
}
